<!--
  @author:  long
  @date:    2023/9/5
  @file:    xx
  @require:
-->
<template>
  <div>
    <el-drawer
      v-model="visible"
      destroy-on-close
      size="40%"
      :close-on-click-modal="false"
      custom-class="columnDrawer"
    >
      <template #header>
        <div>
          <div class="text-xl font-semibold">自定义显示列</div>
          <!--          <p>-->
          <!--            列项显示不得少于5项，最多支持自定义10个列项，灰色选中列不支持隐藏和排序-->
          <!--          </p>-->
        </div>
      </template>
      <el-table
        ref="columnTableRef"
        class="columnTable"
        :data="columnData"
        border
        height="75vh"
        row-key="prop"
      >
        <el-table-column
          type="index"
          label="序号"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column align="center" width="55" label="显示">
          <template #default="scope">
            <el-checkbox
              :checked="selectionColumn.includes(scope.row.prop)"
              @change="
                val => {
                  checkBoxChange(val, scope.row)
                }
              "
            ></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="列名" prop="label"></el-table-column>
        <el-table-column label="拖动调整顺序" width="120" align="center">
          <template>
            <el-icon class="opeartion">
              <Operation />
            </el-icon>
          </template>
        </el-table-column>
      </el-table>
      <!--   底部按钮   -->
      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="dialogConfirm">确认</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="CustomColumn">
import Sortable from 'sortablejs'
import { getCurrentInstance } from 'vue'
import { customerapplyUserDefined } from '@/api/statistical/commercialLoan'

const { proxy } = getCurrentInstance()

const props = defineProps({
  columnData: {
    type: Array,
    default: () => []
  }
})

const data = reactive({
  visible: false,
  columnData: []
})
const { visible, columnData } = toRefs(data)

/**
 * 初始化
 */
const init = () => {
  // 赋值
  columnData.value = props.columnData
  //计算长度与选中的checkId
  getLenAndId()

  // 设置拖拽
  setSortable()
}

const emits = defineEmits(['change'])
const columnTableRef = ref(null)
const selectionColumn = ref([])
const selectLen = ref(0)

/**
 * 计算长度与选中的checkId
 */
const getLenAndId = () => {
  // 选中的id
  selectionColumn.value = columnData.value
    .filter(item => item.isCheckBox)
    .map(item => {
      return item.prop
    })
  // 选中的长度
  selectLen.value = selectionColumn.value.length
  console.info('selectionColumn', selectionColumn.value)
}

/**
 * 设置拖拽
 */
const setSortable = () => {
  proxy.$nextTick(() => {
    const table = document.querySelector(
      '.columnTable .el-table__body-wrapper tbody'
    )
    Sortable.create(table, {
      animation: 150,
      ghostClass: 'blue-background-class',
      // 写完以上部分就已经可以实现基本的拖拽功能了，以下是拓展
      //始拖拽事件
      onEnd: function (/**Event*/ evt) {
        let newIndex = evt.newIndex // 排序后的索引位置
        let oldIndex = evt.oldIndex // 排序前的索引位置
        var itemEl = evt.item // 拖拽 HTMLElement
        evt.to // 目标表
        evt.from // 上一个列表
        evt.oldIndex // 元素在旧父级中的旧索引
        evt.newIndex // 元素在新父级中的新索引
        evt.clone // 克隆元件
        evt.pullMode // 当项目在另一个可排序表中时：`“clone”`如果克隆，`true`如果移动

        const movedData = columnData.value.splice(oldIndex, 1)[0]
        columnData.value.splice(newIndex, 0, movedData)
        getLenAndId()
      },
      //点击选中元素事件
      onChoose: function (/**Event*/ evt) {
        evt.oldIndex
      },
      //取消选中事件
      onUnchoose: function (/**Event*/ evt) {}
    })
  })
}

/**
 *  checkBox选择
 */
const checkBoxChange = (val, row) => {
  row.isCheckBox = val
  console.info('123', columnData.value)

  selectionColumn.value = columnData.value
    .filter(item => item.isCheckBox)
    .map(item => {
      return item.prop
    })

  console.info('selectionColumn.value ', selectionColumn.value)
  // 选中的长度
  selectLen.value = selectionColumn.value.length
}

/**
 * 弹窗打开
 */
const handleDialogOpen = () => {
  visible.value = true
  init()
}

defineExpose({
  handleDialogOpen
})

/**
 * 弹窗关闭
 */
const handleCloseDialog = () => {
  data.visible = false
}

/**
 * 弹窗确认
 */
const dialogConfirm = () => {
  console.info('selectionColumn.value.length', selectionColumn.value.length)

  let params = {
    args: selectionColumn.value.join(',')
  }
  if (params.args == '') {
    params.isExit = 1
  }
  customerapplyUserDefined(params).then(res => {
    handleCloseDialog()
    emits('change')
  })
}
</script>

<style scoped lang="scss">
:deep(.columnDrawer) {
  .el-drawer__header {
    margin-bottom: 10px;
  }
  .el-drawer__body {
    padding: 0 20px 0;
  }
}
</style>
